function r_cor = fsb_calculate_corr(idat,sandbox,slice_n)

% FSB : Calculate reduced maps with reshaped data
%
% EXAMPLE:  r_cor = fsb_trial_corr(idat,sandbox,[10 5 5])
%
% INPUT:
% idat: 4D image data
% sandbox: sandbox experiment struct
% slice_n: number of slice to display
%
% OUTPUT:
% r_cor: correlation matrix data
%
% CALLED BY:
% fsb_calculate_red_map.m
% fsb_corr2d.m
%
% NOTES:
% 
%
% Copyright 2010 MPI for Biological Cybernetics
% Author: Steffen Stoewer
% License:GNU GPL, no express or implied warranties
% 
% $ Revision 1.0
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

%~~~~~~~~~~~~~~~~~
% Transform data to single
%~~~~~~~~~~~~~~~~~
[a b c d] = size(idat);

%~~~~~~~~~~~~~~~~~
% Prepare calculations
%~~~~~~~~~~~~~~~~~

if isfield(sandbox,'r_cor')
    r_cor = sandbox.r_cor;
else
    r_cor = zeros(a,b,c,15);
end

%~~~~~~~~~~~~~~~~~
% Calculate r_cor for slice
%~~~~~~~~~~~~~~~~~
idat_x = shiftdim(idat(:,:,slice_n(3),:),3);
dim_x = size(idat_x);
idat_x = reshape(idat_x,d,[]);
test_x = fsb_corr2d(sandbox.hemodynamics(:,sandbox.hrf_pred),idat_x);
test_x = reshape(test_x,dim_x(2),dim_x(3));
r_cor(:,:,slice_n(3),sandbox.hrf_pred) = test_x;

%~~~~~~~~~~~~~~~~~
% Calculate r_cor for section 1
%~~~~~~~~~~~~~~~~~
idat_y = shiftdim(idat(:,slice_n(2),:,:),3);
dim_y = size(idat_y);
idat_y = reshape(idat_y,d,[]);
test_y = fsb_corr2d(sandbox.hemodynamics(:,sandbox.hrf_pred),idat_y);
test_y = reshape(test_y,dim_y(2),dim_y(3),dim_y(4));
r_cor(:,slice_n(2),:,sandbox.hrf_pred) = test_y;

%~~~~~~~~~~~~~~~~~
% Calculate r_cor for section 2
%~~~~~~~~~~~~~~~~~
idat_z = shiftdim(idat(slice_n(1),:,:,:),3);
dim_z = size(idat_z);
idat_z = reshape(idat_z,d,[]);
test_z = fsb_corr2d(sandbox.hemodynamics(:,sandbox.hrf_pred),idat_z);
test_z = reshape(test_z,dim_z(2),dim_z(3),dim_z(4));
r_cor(slice_n(1),:,:,sandbox.hrf_pred) = test_z;

end
